package cc.fs.zhihuapp.ui.activity.demo;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cc.fs.zhihuapp.R;
import cc.fs.zhihuapp.ui.activity.helper.BaseActivity;
import cc.fs.zhihuapp.utils.FileUtil;
import cc.fs.zhihuapp.utils.PhoneDevices;
import cc.fs.zhihuapp.utils.RecordVideo;

/**
 * Created by fostion on 2015/11/7.
 * 这个是里一个手机录制视频然后编码的的demo
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class RecordCameraActivity extends BaseActivity implements SurfaceHolder.Callback, OnErrorListener {

    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.btn)
    ImageView btn;
    @InjectView(R.id.rootView)
    RelativeLayout rootView;
    @InjectView(R.id.surfaceView)
    SurfaceView surfaceView;
    @InjectView(R.id.timebar)
    ProgressBar timebar;

    SurfaceHolder surfaceHolder;
    Camera camera;
    RecordVideo recordVideo;

    public int MAX_TIME = 16000;
    public long downTime;
    public long upTime;
    private boolean isRecording = false;


    private void d(String msg) {
        Log.d(" RecordCameraActivity  ", msg);
    }

    private Timer timer;
    private TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            long currentTime = System.currentTimeMillis();
            final int restTime = MAX_TIME - ((Number) (currentTime - downTime)).intValue();
            if (restTime > 0) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!isRecording) {
                            if (recordVideo != null && recordVideo.start(FileUtil.getCachePath(_this, "video.mp4"))) {
                                isRecording = true;
                                T("开始录制视频");
                            }
                        }
                        timebar.setProgress(restTime);
                    }

                });
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        timebar.setProgress(0);
                        recordVideo.stop();
                        timer.cancel();
                        T("录制结束");
                        finish();
                    }
                });
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_record_camera);
        ButterKnife.inject(this);

        toolbar.setTitle("录制demo");
        setSupportActionBar(toolbar);

        if (!PhoneDevices.isHasCameraDevices(this)) {
            T("手机没有摄像头，程序结束!");
//            finish();
        }

        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        timebar.setMax(MAX_TIME);
        timebar.setProgress(MAX_TIME);

        btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        timebar.setMax(MAX_TIME);
                        timebar.setProgress(MAX_TIME);
                        downTime = System.currentTimeMillis();
                        timer = new Timer();
                        timer.schedule(timerTask, 0, 80);
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        upTime = System.currentTimeMillis();
                        timer.cancel();
                        timer = null;
                        break;
                }
                return false;
            }
        });

//        btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
////                if (recordVideo != null && recordVideo.start(FileUtil.getCachePath(_this, "video.mp4"))) {
////                    Toast.makeText(_this, "开始录制视频", Toast.LENGTH_SHORT).show();
////                }
//            }
//        });
    }

    @Override
    public void handler(Message msg) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        camera = Camera.open(0);
        if (camera != null) {
            Camera.Parameters parameters = camera.getParameters();
            camera.setParameters(parameters);
            recordVideo = new RecordVideo(camera, surfaceHolder);
        } else {
            T( "摄像头打开错误!");
        }
    }


    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if (camera != null) {
            try {
                Camera.Parameters parameters = camera.getParameters();
                parameters.setPreviewSize(width, height);
                parameters.setPictureFormat(PixelFormat.JPEG);
                camera.setParameters(parameters);
                camera.setPreviewDisplay(holder);
                camera.setDisplayOrientation(90);
                camera.startPreview();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (camera != null) {
            if (recordVideo != null)
                recordVideo.stop();
            camera.stopPreview();
            camera.release();
            d(" 结束程序,释放资源! ");
        }
    }

    @Override
    protected void onDestroy() {
        if (recordVideo != null)
            recordVideo.stop();
        super.onDestroy();
    }

    @Override
    public void onError(MediaRecorder mr, int what, int extra) {
        d("recore error  what " + what + "   extra " + extra);
        if (mr != null) {
            mr.reset();
        }
    }
}
